'''
Created on Dec 27, 2012

@author: Ben
'''
#!/usr/bin/python

import os
import shutil
import platform
import sys
import fnmatch
import re

sabCompletePath = ''
sabInCompletePath = ''
sickBeardRoot = ''
osUser = os.path.expanduser('~')
tvList = ()

#like walk but will only go as deep as you like
def walklevel(some_dir, level):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

#Reads what directories have already been created. 
def existingDirectories():
    return os.listdir(sickBeardRoot)      

#Get props for sabNZB            
def sabNZBProps():

    #Default path according to sab docs 
    global osUser 
    osUser = os.path.expanduser('~')
    sabConfigFile = 'sabnzbd.ini'
    global sabCompletePath
    global sabInCompletePath

    if platform.system() == 'Windows' and platform.release() == 'XP' :
        sabConfigPath = osUser + '\Local Settings\Application Data\\'
    elif platform.system() == 'Windows' and platform.release() == '7' :
        sabConfigPath = osUser + '\AppData\Local\sabnzbd\\'
    elif platform.system() == 'Unix' :
        sabConfigPath = '~/.sabnzbd/'
    elif platform.system() == 'Linux' :
        sabConfigPath = osUser + '/.sabnzbd/'        
    else :
        print 'path not found'
        sys.exit()

    with open(sabConfigPath + sabConfigFile, 'r') as f:
        for line in f.readlines():    
            if line.startswith('complete_dir') :
                sabCompletePath = line.lstrip('complete_dir = ').rstrip('\n')
            elif line.startswith('download_dir') :
                sabInCompletePath = line.lstrip('download_dir = ').rstrip('\n')
    f.closed    
    
#Get props for sickbeard. To be used with slotting new files into correct directories     
def sickBeardProps():

    #Default path according to sick beard 
    sickBeardConfigFile = 'config.ini'
    sickBeardConfigPath = ''
    global sickBeardRoot
    global osUser

    if platform.system() == 'Windows' and platform.release() == 'XP' :
        sickBeardConfigPath = osUser + '\Local Settings\Application Data\\'
    elif platform.system() == 'Windows' and platform.release() == '7' :
        sickBeardConfigPath = osUser + '\AppData\Local\\'
    elif platform.system() == 'Unix' :
        sickBeardConfigPath = '~/.'
    elif platform.system() == 'Linux' :
        sickBeardConfigPath = osUser + '/.'        
    else :
        print 'path not found'
        sys.exit()

    listDirs = os.listdir(osUser)            
    
    # start with the user directory and walk the tree
    for line in listDirs :
        if line.startswith('SickBeard') or line.startswith('Sick-Beard-master') :
            sickBeardRoot = osUser + os.path.sep + line.rstrip('\n')
            for root, dirs, files in walklevel(sickBeardRoot,2) :
                for file1 in files :
                    if fnmatch.fnmatch(file1, sickBeardConfigFile):                
                        with open(os.path.join(root,file1), 'r') as f:
                            for line in f.readlines():    
                                if line.startswith('root_dirs') :
                                    sickBeardRoot = line.lstrip('root_dirs = ').rstrip('\n').lstrip('0|')
                        f.closed        
                        
#Get the list of items that are completed                         
def listVideoFiles(tvList):
    seasonAndEpStr = ''
    # Search for avi, mkv or mp4 
    for root, dirs, files1 in walklevel(osUser + os.path.sep + sabCompletePath,1) :    
        for file1 in files1 :
            fileToSearch = file1.lower()
            #print fileToSearch
            
            # exclude anything that has the word sample in it. 
            if (fileToSearch.endswith(('.avi', '.mkv', '.mp4')) and fileToSearch.find('sample') == -1):
                for tv in tvList:
                    #Remove periods, brackets, hypens, underscores
                    #print fileToSearch.replace('.',' ').replace('(','').replace(')','').replace('-',' ').replace('_',' ')
                    #print file1 
                    if fileToSearch.replace('.',' ').replace('(','').replace(')','').replace('-',' ').replace('_',' ').find(tv.lower().replace('(','').replace(')','')) <> -1 :
                            seasonAndEp = re.search('([Ss]0)([0-9]{1,2})([xXeE\.\-]?)([0-9]{1,2})',file1)
                            #try matching without the S
                            if seasonAndEp == None:
                                seasonAndEpStr = re.search('([0-9]{1,2})([xXeE\.\-])([0-9]{1,2})', file1).group(0)
                                
                                # add an S and replace the x 
                                if seasonAndEpStr <> None:
                                    seasonAndEpStr = re.sub('[xX]','E','S' + seasonAndEpStr)
                            else :
                                seasonAndEpStr = seasonAndEp.group(0)
                                
                            if seasonAndEpStr == None:
                                os.rename(root + os.path.sep + file1, sickBeardRoot + os.path.sep + tv + os.path.sep + tv + ' Special' + file1[-4:])
                                # Don't ignore errors in this case
                                shutil.rmtree(root)
                            else:
                                print sickBeardRoot + os.path.sep + tv + os.path.sep + tv + ' ' + seasonAndEpStr + file1[-4:]
                                os.rename(root + os.path.sep + file1, sickBeardRoot + os.path.sep + os.path.sep + tv + os.path.sep + tv + ' ' + seasonAndEpStr + file1[-4:])
                                shutil.rmtree(root, ignore_errors=1)
                            # rename does the same thing as move but in one step. There are issues with it though. 
                            #shutil.move(root + os.path.sep + file1, sickBeardRoot + os.path.sep + tv + os.path.sep + file1)    
                         
sabNZBProps()    
sickBeardProps()
listVideoFiles(list(existingDirectories()))









    
